package com.my.blogapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.blogapi.dao.mapper.TagMapper;
import com.my.blogapi.dao.pojo.Tag;
import com.my.blogapi.service.TagService;
import com.my.blogapi.vo.TagVo;
import com.my.blogapi.vo.param.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {

    @Resource
    private TagMapper tagMapper;

    /**
     * 查询最热标签
     * @param limit
     * @return
     */
    @Override
    public Result findTagsByLimit(int limit) {
        //获取最多文章的前六条tag_id
        List<Long> tagIds = tagMapper.findHotTagBylimit(limit);
        //通过tag_id查询对应分标签名称
        if (CollectionUtils.isEmpty(tagIds)){
            return Result.success(Collections.emptyList());
        }
        //不为空后查询对应的tagName
        List<Tag> list =tagMapper.findTagsByTagIds(tagIds);
        return Result.success(list);
    }

    @Override
    public Result findAll() {
        List<Tag> tagList = tagMapper.selectList(new LambdaQueryWrapper<>());
        return Result.success(copylist(tagList));
    }

    @Override
    public Result findDetailById(Long id) {
        Tag tag = tagMapper.selectById(id);
        TagVo copy = copy(tag);
        return Result.success(copy);
    }

    @Override
    public List<TagVo> findTagsByArticleId(Long articleId) {
        List<Tag> tagList = tagMapper.findTagsByArticleId(articleId);
        return copylist(tagList);
    }

    private List<TagVo> copylist(List<Tag> tagList) {
        ArrayList<TagVo> list = new ArrayList<>();
        for (Tag tag : tagList) {
            list.add(copy(tag));
        }
        return list;
    }

    private TagVo copy(Tag tag) {
        TagVo tagVo = new TagVo();
        BeanUtils.copyProperties(tag,tagVo);
        return tagVo;
    }


}
